/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014-6-10         luwei
 */

package com.tianci.appstore.ui.mainpage;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.R;
import com.tianci.appstore.audio.IAudio;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.control.SkyMainPageController;
import com.tianci.appstore.ui.data.SkyAppDetailData;
import com.tianci.appstore.ui.loading.LoadingView;
import com.tianci.appstore.ui.widget.LeftImageButtonLayer;
import com.tianci.appstore.ui.widget.SkyAppPager;
import com.tianci.appstore.ui.widget.SkyAppPager.Direction;
import com.tianci.appstore.ui.widget.SkyBaseItemView;
import com.tianci.appstore.ui.widget.SkyCategoryBar;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.SkyCustomLayout.BlockData;
import com.tianci.appstore.ui.widget.SkyCustomLayout.CustomLayoutParams;
import com.tianci.appstore.ui.widget.SkyGridAdapter;
import com.tianci.appstore.ui.widget.SkyGridAdapter.AdapterType;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.List;

public class SkyAppStoreMainPage extends RelativeLayout {
    private SkyAppPager mPager = null;
    private Context mContext = null;
    private SkyCategoryBar mCategoryBar = null;
    private SkyMainPageController mController = null;
    private LeftImageButtonLayer mButtonLayer = null;
    private List<View> mLayouts = new ArrayList<View>();
    protected LoadingView loadingView;
    private TextView mTips = null;
    private boolean managePageAdded = false;

    public SkyAppStoreMainPage(Context context) {
        super(context);
//        LogUtils.d("mytime", "------1.");
        this.mContext = context;
//        SkinManager.setBackground(this, R.drawable.bg);
//        LogUtils.d("mytime", "------2.");
        mController = new SkyMainPageController(mContext);
        mController.setMainPageLayout(this);
//        LogUtils.d("mytime", "------3.");
//        addDivideLine();
//        LogUtils.d("mytime", "------4.");
        addCategoryBar();
//        LogUtils.d("mytime", "------5.");
        addButtonsLayer();
//        LogUtils.d("mytime", "------6.");
        addContentView();
//        LogUtils.d("mytime", "------7.");
        setController();
        initDefaultLayout(0);
//        LogUtils.d("mytime", "------8.");
        addLoadingView();
//        LogUtils.d("mytime", "------9.");
        setLoadingVisible(true);
//        LogUtils.d("mytime", "------10.");
        SkinManager.setBackground(this, R.drawable.ui_sdk_app_bg);
    }

    public void setLoadingVisible(boolean visible) {
        if (visible) {
            loadingView.startLoading();
        } else {
            loadingView.stopLoading();
        }
    }

    public IAudio getAudioInterface() {
        return mController;
    }

    public void setCategoryFocus() {
        mController.setCategoryFocus();
    }

    private void addLoadingView() {
        loadingView = new LoadingView(mContext);
        this.addView(loadingView, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        loadingView.setVisibility(View.INVISIBLE);
    }

    public void onResume() {
        if (mController != null) {
            mController.onResume();
        }
    }

    public boolean setFocusToRecommand() {
        if (mController != null) {
            return mController.setFocusToRecommand();
        }
        return false;
    }

    private void addDivideLine() {
        ImageView imageView = new ImageView(mContext);
        SkinManager.setBackground(imageView, R.drawable.pic_line);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.setMargins(0, SkyConstants.Div(97), 0, 0);
        imageView.setLayoutParams(params);
        addView(imageView);
    }

    private void addCategoryBar() {
        mCategoryBar = new SkyCategoryBar(mContext);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                SkyConstants.Div(1400), SkyConstants.Div(200));
        params.setMargins(SkyConstants.Div(110), SkyConstants.Div(85), 0, 0);
        mCategoryBar.setLayoutParams(params);
        mCategoryBar.setCategoryChangeListener(mController);
        addView(mCategoryBar);
        mCategoryBar.requestFocus();
    }

    private void addButtonsLayer() {
        mButtonLayer = new LeftImageButtonLayer(mContext);
        mButtonLayer.setInMainPage(true);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.setMargins(0, SkyConstants.Div(85), SkyConstants.Div(124), 0);
        mButtonLayer.setLayoutParams(params);
        mButtonLayer.initDefaultParams();
        addView(mButtonLayer);
    }

    private void addContentView() {
        mPager = new SkyAppPager(mContext, Direction.HORIZONTAL);
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        this.addView(mPager, params1);
    }

    private void setController()
    {
        mController.setAppPager(mPager);
        mController.setCategoryBar(mCategoryBar);
        mController.setButtonLayer(mButtonLayer);
    }

    public void initDefaultLayout(int num) {
        initMyAppPage();
        for (int i = 0; i < num; i++) {
            SkyCustomLayout layout = initCommonLayout();
            mPager.addView(layout);
        }
//        initManagePage();
    }

    public void updateAppStatus(String pkgName, SkyAppDetailData.AppStatus status) {
        LogUtils.d("test", "updateAppStatus  pkg:" + pkgName + " status:" + status);
        int count = mPager.getChildCount();
        for (int i = 0; i < count; i++) {
            if (!(mPager.getChildAt(i) instanceof SkyCustomLayout))
                continue;
            SkyCustomLayout child = (SkyCustomLayout) mPager.getChildAt(i);
            for (View view : child.getChildViews()) {
                if (view instanceof SkyBaseItemView) {
                    SkyBaseItemView block = (SkyBaseItemView) view;
                    if ((block.getData()).getPackageName() != null && ((block.getData()).getPackageName().equals(pkgName))) {
                        if (block instanceof MainBigBlock) {
                            ((MainBigBlock) block).updateStatus(status);
                        } else if (block instanceof MainSmallBlock) {
                            ((MainSmallBlock) block).updateStatus(status);
                        }
                    }
                }
            }
        }
    }

    public void showTipsView(String tips) {
        if (mTips == null) {
            mTips = new TextView(mContext);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            mTips.setLayoutParams(params);
            mTips.setTextSize(SkyConstants.Dpi(46));
            mTips.setTextColor(Color.WHITE);
            addView(mTips);
        }
        mTips.setVisibility(View.VISIBLE);
        mTips.setText(tips);
    }

    public void hideTipsView() {
        if (mTips != null) {
            mTips.setVisibility(View.GONE);
        }
    }

    public SkyCustomLayout initCommonLayout() {
        SkyCustomLayout layout = new SkyCustomLayout(mContext, CoocaaApplication.mDiv);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, Gravity.CENTER_HORIZONTAL);
        layout.setLayoutParams(params);
        CustomLayoutParams netAppParams = new CustomLayoutParams();
        netAppParams.mRow = 3;
        netAppParams.mCol = 7;
        netAppParams.mBlockWidth = SkyConstants.Div(getResources().getDimensionPixelSize(R.dimen.net_block_width));
        netAppParams.mBlockHeight = SkyConstants.Div(getResources().getDimensionPixelSize(R.dimen.net_block_width));
        netAppParams.mHorizontalSpace = SkyConstants.Div(getResources().getDimensionPixelSize(R.dimen.net_v_space));
        netAppParams.mVerticalSpace = SkyConstants.Div(getResources().getDimensionPixelSize(R.dimen.net_v_space));
        //netAppParams.mMarginLeft = SkyConstants.Div(97);
        netAppParams.mMarginTop = SkyConstants.Div(188);
        layout.setCustomLayoutParams(netAppParams);
        layout.setBlockDatas(generateNetAppBlockData());
        SkyGridAdapter mAdapter = new SkyGridAdapter(mContext, CoocaaApplication.mDiv,
                AdapterType.MAIN_TYPE);
        // mAdapter.setClickListener(mController);
        mAdapter.setKeyListener(mController);
        layout.setAdapter(mAdapter);
        return layout;
    }

    private void initManagePage() {
        SkyCustomLayout layout = new SkyCustomLayout(mContext, CoocaaApplication.mDiv);
        layout.setBlockNum(3, 3);
        layout.setBlockSize(SkyConstants.Div(600), SkyConstants.Div(271));
        layout.setVerticalSpace(SkyConstants.Div(-42));
        layout.setHorizontalSpace(SkyConstants.Div(-42));
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, Gravity.CENTER_HORIZONTAL);
        layout.setLayoutParams(params);
        layout.setMargin(SkyConstants.Div(0), SkyConstants.Div(188), SkyConstants.Div(0), 0);
        layout.setBlockDatas(generateManageBlockData());
        SkyGridAdapter mAdapter = new SkyGridAdapter(mContext, CoocaaApplication.mDiv, AdapterType.MANAGE_TYPE);
//        mAdapter.setClickListener(mController);
        mAdapter.setKeyListener(mController);
        layout.setAdapter(mAdapter);
        mPager.addView(layout);
        managePageAdded = true;
    }

    private void initMyAppPage() {
        SkyMyAppPage page = new SkyMyAppPage(mContext, Direction.HORIZONTAL);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER);
        page.setLayoutParams(params);
        mPager.addView(page);
        mController.setMyAppController(page.getController());
        page.getController().setPageBoundaryListener(mController);
    }


//    public void addMoreAppPage(int num)
//    {
//        for (int i = 0; i < num; i++)
//        {
//            initMyAppPage();
//        }
//    }

    public void onDestory() {
        if (mButtonLayer != null) {
            mButtonLayer.onDestory();
        }
        if (mCategoryBar != null) {
            mCategoryBar.onDestory();
        }
        if (mController != null)
            mController.destory();
    }

    public void reSizePager(int totalPage) {
        int temp = totalPage - mPager.getChildCount();
        if (temp > 0) {
            for (int i = 0; i < temp; i++) {
                if (i == temp - 1 && !managePageAdded) {
                    initManagePage();
                } else {
                    if (mLayouts.size() == 0) {
                        SkyCustomLayout layout = initCommonLayout();
                        if (managePageAdded)
                            mPager.addView(layout, mPager.getChildCount() - 1);
                        else
                            mPager.addView(layout);
                    } else {
                        if (managePageAdded)
                            mPager.addView(mLayouts.remove(0), mPager.getChildCount() - 1);
                        else
                            mPager.addView(mLayouts.remove(0));
                    }
                }
            }
        } else if (totalPage > 1) {
            for (int i = 0; i < Math.abs(temp); i++) {
                if (mPager.getChildCount() - 1 > 0) {
                    View view = mPager.getChildAt(mPager.getChildCount() - 2);
                    mLayouts.add(view);
                    mPager.removeViewAt(mPager.getChildCount() - 2);
                }
            }
        }
    }


    private List<BlockData> generateNetAppBlockData() {
        List<BlockData> datas = new ArrayList<BlockData>();
        BlockData data1 = new BlockData();
        data1.mColNum = 1;
        data1.mRowNum = 1;
        data1.mBlock = new int[]{0};
        data1.mTurnPage = new boolean[]{true, false, false, false};
        datas.add(data1);

        BlockData data2 = new BlockData();
        data2.mColNum = 1;
        data2.mRowNum = 1;
        data2.mBlock = new int[]{7};
        data2.mTurnPage = new boolean[]{true, false, false, false};
        datas.add(data2);

        BlockData data3 = new BlockData();
        data3.mColNum = 1;
        data3.mRowNum = 1;
        data3.mBlock = new int[]{14};
        data3.mTurnPage = new boolean[]{true, false, false, false};
        datas.add(data3);

        BlockData data4 = new BlockData();
        data4.mColNum = 2;
        data4.mRowNum = 2;
        data4.mBlock = new int[]{1, 2, 8, 9};
        data4.mTurnPage = new boolean[]{false, false, false, false};
        datas.add(data4);

        BlockData data5 = new BlockData();
        data5.mColNum = 2;
        data5.mRowNum = 2;
        data5.mBlock = new int[]{3, 4, 10, 11};
        data5.mTurnPage = new boolean[]{false, false, false, false};
        datas.add(data5);

        BlockData data6 = new BlockData();
        data6.mColNum = 2;
        data6.mRowNum = 2;
        data6.mBlock = new int[]{5, 6, 12, 13};
        data6.mTurnPage = new boolean[]{false, false, true, false};
        datas.add(data6);

        for (int i = 15; i < 21; i++) {
            BlockData data = new BlockData();
            data.mColNum = 1;
            data.mRowNum = 1;
            data.mBlock = new int[]{i};
            if (i == 20) {
                data.mTurnPage = new boolean[]{false, false, true, false};
            } else {
                data.mTurnPage = new boolean[]{false, false, false, false};
            }
            datas.add(data);
        }
        return datas;
    }

    private List<BlockData> generateManageBlockData() {
        List<BlockData> datas = new ArrayList<BlockData>();
        for (int i = 0; i < 9; i++) {
            BlockData data1 = new BlockData();
            data1.mColNum = 1;
            data1.mRowNum = 1;
            data1.mBlock = new int[]{i};
            if (i % 3 == 0) {
                data1.mTurnPage = new boolean[]{true, false, false, false};
            } else if ((i + 1) % 3 == 0) {
                data1.mTurnPage = new boolean[]{false, false, true, false};
            } else {
                data1.mTurnPage = new boolean[]{false, false, false, false};
            }
            datas.add(data1);
        }
        return datas;
    }


}
